package com.medical.system.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.medical.system.converter.UserOlineConverter;
import com.medical.system.model.entity.SysUserOnline;
import com.medical.system.model.vo.UserOnlinePageVO;
import com.medical.system.service.SysUserOnlineService;
import com.medical.satoken.constant.SaTokenConstant;
import com.medical.system.model.query.UserOnlinePageQuery;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@RequiredArgsConstructor
@Slf4j
@Service
public class SysUserOnlineServiceImpl  implements SysUserOnlineService {

    private final UserOlineConverter userOlineConverter;

    @Override
    public IPage<UserOnlinePageVO> pageUserOnline(UserOnlinePageQuery queryParam) {
        int pageNum = queryParam.getPageNum();
        int pageSize = queryParam.getPageSize();
        // 返回数据对象
        List<UserOnlinePageVO> list = new ArrayList<>();
        // 获取所有登录的用户ids
        List<String> tokenList = StpUtil.searchTokenValue("", 0, -1, false);
        for (int i = pageNum * pageSize, len = Math.min(pageSize + i, tokenList.size()); i < len; i++) {
            SaSession session =  StpUtil.getTokenSessionByToken(tokenList.get(i));
            SysUserOnline userOnline = session.getModel(SaTokenConstant.USER_ONLINE, SysUserOnline.class);
            list.add(userOlineConverter.entity2PageVO(userOnline));
        }
        return new Page<UserOnlinePageVO>().setTotal(tokenList.size()).setRecords(list);
    }

    @Override
    public void kickoutByTokenValue(String tokenValue) {
        StpUtil.kickoutByTokenValue(tokenValue);
    }
}
